package com.example.monitoringsystem.controller;

import com.example.monitoringsystem.bean.User;
import com.example.monitoringsystem.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @GetMapping("/{url}")
    public String redirect(@PathVariable("url") String url) {
        return url;
    }

    @PostMapping(value = "/load")
    public String login(String account, String password, Model model) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        try {
            //将账号和密码通过token传给shiro进行认证
            subject.login(token);
            User user = (User) subject.getPrincipal();
            subject.getSession().setAttribute("user", user);
            switch (user.getRole().toString()){
                case "doctor":
                    break;
                case "patient":
                    return "patient";
                case "admini":
                    break;
                default:
                    break;
            }
            return "patient";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            model.addAttribute("msg", "账号不存在");
            return "load";
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            model.addAttribute("msg", "密码有误");
            return "load";
        }
    }
}
